<template>
    <div class="add-order-information-view">

        <el-form
                ref="refForm"
                :model="datas"
                :inline="true"
                :rules="rules"
                label-position="right"
                size="small"
                class="filter-form-inline"
                label-width="120px"
        >
            <el-row :gutter="40">

                <el-col
                        v-if="datas.orderType == 1"
                        :span="8"
                >
                    <el-form-item
                            label="配送商名称："
                            prop="distributeId"
                    >
                        <el-select
                                v-model="datas.distributeId"
                                placeholder="请选择配送商"
                                :disabled="(datas.id>0 || list.length > 0)"
                                @change="distributeChange"
                        >
                            <el-option
                                    v-for="item in distributeOps"
                                    :key="item.distributeId"
                                    :label="item.distributeName"
                                    :value="item.distributeId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col
                        v-else-if="datas.orderType == 2"
                        :span="8"
                >
                    <el-form-item
                            label="终端名称："
                            prop="terminalId"
                    >
                        <el-select
                                v-model="datas.terminalId"
                                placeholder="请选择终端"
                                :disabled="(datas.id>0 || list.length > 0)"
                                @change="terminalChange"
                        >
                            <el-option
                                    v-for="item in terminalOps"
                                    :key="item.terminalId"
                                    :label="item.terminalName"
                                    :value="item.terminalId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col
                        v-if="datas.orderType == 1"
                        :span="8"
                >
                    <el-form-item
                            label="订单是否分户："
                            prop="planMode"
                    >
                        <el-select
                                @change="splitChange"
                                :disabled="(datas.id>0 || list.length > 0)"
                                v-model="datas.isSplit"
                                placeholder="请选择订单是否分户"
                        >
                            <el-option
                                    label="分户"
                                    value="2"
                            />
                            <el-option
                                    label="非分户"
                                    value="1"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col
                        v-if="datas.isSplit == 2 || datas.orderType == 3"
                        :span="8"
                >
                    <el-form-item
                            label="代理名称："
                            prop="agentName"
                    >
                        <el-autocomplete
                                v-model="datas.agentName"
                                :disabled="(datas.id>0 || list.length > 0)"
                                style="width: 100%"
                                placeholder="请输入代理商名称"
                                :fetch-suggestions="querySearchAsyncAgent"
                                @select="handleSelectAgent"
                        >
                            <template #default="{ item }">
                                <div class="distributeName" v-if="item.agentType == 'agent'">{{ item.agentName }}</div>
                                <div class="distributeName" v-else>{{ item.userName }}</div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                </el-col>

                <el-col
                        v-if="datas.orderType == 4"
                        :span="8"
                >
                    <el-form-item
                            label="商销客户名称："
                            prop="sellerName"
                    >
                        <el-autocomplete
                                v-model="datas.sellerName"
                                style="width: 100%"
                                :disabled="(datas.id>0 || list.length > 0)"
                                placeholder="请输入商销客户名称"
                                :fetch-suggestions="querySearchAsyncSeller"
                                @select="handleSelectSeller"
                        >
                            <template #default="{ item }">
                                <div class="distributeName">{{ item.sellerName }}</div>
                            </template>
                        </el-autocomplete>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item
                            label="下单日期："
                            prop="putOrderTime"
                    >
                        <date-picker
                                v-model:date="datas.putOrderTime"
                                placeholder="请选择下单日期"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item
                            label="收款类型："
                            prop="receiveMoneyType"
                    >
                        <el-select
                                v-model="datas.receiveMoneyType"
                                placeholder="请选择收款类型"
                        >
                            <el-option
                                    v-for="item in moneyTypes"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item
                            label="负责营销职员："
                            prop="headId"
                    >
                        <el-select
                                v-model="datas.headId"
                                placeholder="请选择负责营销职员"
                                clearable
                                @change="headChange"
                        >
                            <el-option
                                    v-for="item in headOptions"
                                    :key="item.id"
                                    :label="item.realName"
                                    :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">

                    <el-form-item
                            label="收货地址："
                            prop="acceptAddress"
                    >
                        <el-input
                                v-model="datas.acceptAddress"
                                placeholder="请输入地址"
                        >
                            <template #append>
                                <el-button
                                        style="padding: 0px 5px"
                                        type="text"
                                        @click="addressClick"
                                >选择</el-button>
                            </template>

                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">

                    <el-form-item
                            label="收货人："
                            prop="acceptUser"
                    >
                        <el-input
                                v-model="datas.acceptUser"
                                placeholder="请输入收货人"
                        >
                            <template #append>
                                <el-button
                                        style="padding: 0px 5px"
                                        type="text"
                                        @click="contactClick"
                                >选择</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">

                    <el-form-item
                            label="收货人电话："
                            prop="acceptTel"
                    >
                        <el-input
                                v-model="datas.acceptTel"
                                placeholder="请输入收货人电话"
                        />
                    </el-form-item>
                </el-col>

                <!--        <el-col-->
                <!--          v-if="datas.isSplit == 2"-->
                <!--          :span="8"-->
                <!--        >-->
                <!--          <el-form-item-->
                <!--            label="客户类型："-->
                <!--            prop="agentType"-->
                <!--          >-->
                <!--            <el-select-->
                <!--              v-model="datas.agentType"-->
                <!--              placeholder="请选择客户类型"-->
                <!--              :disabled="(datas.id>0 || list.length > 0)"-->
                <!--              @change="typeChange"-->
                <!--            >-->
                <!--              <el-option-->
                <!--                v-for="item in clientOps.filter(item=>{return item.value != 'direct'})"-->
                <!--                :key="item.value"-->
                <!--                :label="item.label"-->
                <!--                :value="item.value"-->
                <!--              />-->
                <!--            </el-select>-->
                <!--          </el-form-item>-->
                <!--        </el-col>-->




                <el-col :span="8">
                    <el-form-item
                            label="期望交货日期："
                            prop="expireDeliveryTime"
                    >
                        <date-picker
                                v-model:date="datas.expireDeliveryTime"
                                placeholder="请选择期望交货日期"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item :label="datas.orderType == 4 ? '关联客户合同' : datas.orderType == 3 ? '关联代理合同' : datas.orderType == 2 ? '关联终端合同' : datas.isSplit == 2 ? '关联代理合同' : '关联配送合同'">
                        <el-select
                                v-model="datas.contractId"
                                placeholder="请选择关联合同"
                                clearable
                        >
                            <el-option
                                    v-for="item in contractOptions"
                                    :key="item.id"
                                    :label="item.contractName"
                                    :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>



            </el-row>
        </el-form>

        <el-form
                :model="datas"
                label-position="right"
                size="small"
                class="filter-form-inline"
                label-width="120px"
        >

            <el-row>

                <el-col :span="24">
                    <el-form-item label="备注：">
                        <el-input
                                v-model="datas.remark"
                                :rows="2"
                                type="textarea"
                                placeholder="请输入备注"
                        />
                    </el-form-item>
                </el-col>

            </el-row>
        </el-form>

        <address-dialog
                ref="addresRef"
                @confirm="addressConfirm"
        />

        <contact-dialog
                ref="contactRef"
                @confirm="contactConfirm"
        />

    </div>
</template>

<script>
    import {
        validateVETel,
    } from "@/utils/validate";
import {crmStore} from '@CRM/store'
import {defineComponent, defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'

export default defineComponent({
        name: 'Information',
    emits:['change'],
        components: {
            addressDialog:defineAsyncComponent(()=>import('./addressDialog.vue')),
            contactDialog:defineAsyncComponent(()=>import('./contactDialog.vue'))
        },
        props: {
            datas: {
                type: Object,
                default: {},
            },
            list: {
                type: Array,
                default: [],
            },
        },
        setup(props, { emit }) {
            const currentInstance = getCurrentInstance()
            const api = inject('api')
            const checkPhone = (rule, value, callback) => {
                if (!value) {
                    callback(new Error('请输入收货人电话'))
                } else {
                    if (validateVETel(value)) {
                        callback(new Error("电话格式不正确"));
                    } else {
                        callback();
                    }
                }
            }
            const rules = ref({
                distributeId: [
                    {
                        required: true,
                        message: '请选择配送商',
                        trigger: 'change',
                    },
                ],
                terminalId: [
                    {
                        required: true,
                        message: '请选择终端',
                        trigger: 'change',
                    },
                ],
                putOrderTime: [
                    {
                        type: 'date',
                        required: true,
                        message: '请选择下单日期',
                        trigger: 'change',
                    },
                ],
                acceptAddress: [
                    {
                        required: true,
                        message: '请输入收货地址',
                        trigger: 'blur',
                    },
                ],
                acceptUser: [
                    {
                        required: true,
                        message: '请输入收货人',
                        trigger: 'blur',
                    },
                ],
                acceptTel: [
                    {
                        required: true,
                        validator: checkPhone,
                        trigger: 'blur',
                    },
                ],
                receiveMoneyType: [
                    {
                        required: true,
                        message: '请选择收款类型',
                        trigger: 'change',
                    },
                ],
                agentType: [
                    {
                        required: true,
                        message: '请选择客户类型',
                        trigger: 'change',
                    },
                ],
                agentName: [
                    {
                        required: true,
                        message: '请选择客户',
                        trigger: 'change',
                    },
                ],
                sellerName: [
                    {
                        required: true,
                        message: '请选择商销客户',
                        trigger: 'change',
                    },
                ],
                expireDeliveryTime: [
                    {
                        type: 'date',
                        required: true,
                        message: '请选择期望交货日期',
                        trigger: 'change',
                    },
                ],
                headId: [
                    {
                        required: true,
                        message: '请选择营销职员',
                        trigger: 'change',
                    },
                ],
            })
            const types = crmStore.getters['dictionary/getDictionary']['order_type']
            const moneyTypes =
                crmStore.getters['dictionary/getDictionary']['receive_money_type']

            const clientOps = ref([
                {
                    label: '代理',
                    value: 'agent',
                },
                {
                    label: '兼职',
                    value: 'agent_person',
                },
                {
                    label: '终端直销',
                    value: 'direct',
                },
            ])
            var data = reactive({
                addresRef: null,
                contactRef: null,
                headOptions: crmStore.getters['company/getHeadOptions'],
                distributeOps: [],
                terminalOps: [],
                contractOptions: [],
                agentOptions: [],
                refForm: null,
            })

            const addressClick = () => {
                console.log(props.datas)
                data.addresRef.openDialog(props.datas)
            }

            const contactClick = () => {
                data.contactRef.openDialog(props.datas)
            }

            const headChange = (val) => {
                if (val) {
                    const index = data.headOptions.findIndex((a) => a.id == val)
                    if (index != -1) {
                        props.datas.headName = data.headOptions[index].realName
                    }
                } else {
                    props.datas.headId = ''
                    props.datas.headName = ''
                }
            }

            const splitChange = () => {
                data.contractOptions = []
                props.datas.agentName = ''
                props.datas.agentId = 0
                props.datas.contractId = ''
                if (props.datas.isSplit == 1 && props.datas.distributeId){
                    getContract('distribute',props.datas.distributeId)
                }else if (props.datas.isSplit == 2 && props.datas.agentId) {
                    getContract(props.datas.agentType,props.datas.agentId)
                }
            }

            const getContract = (type,id) => {
                data.contractOptions = []
                // props.datas.contractId = ''

                const a = {
                    objectId: id,
                    contractObjectType: type,
                }
                api.common.VALID_CONTRACT_LIST(a).then((res) => {
                    if (!res.code && res.data) {
                        data.contractOptions = res.data.list
                    }
                })
            }

            const agentChange = (val) => {
                props.datas.contractId = ''
                if (val) {
                    getContract()
                } else {
                    data.contractOptions = []
                }
                emit('change')
            }

            const distributeChange = (val) => {
                if (val) {
                    const index = data.distributeOps.findIndex((a) => a.distributeId == val)
                    if (index != -1) {
                        const a = data.distributeOps[index]
                        if (a.defaultAddressStr) {
                            props.datas.acceptAddress = a.defaultAddressStr
                        }

                        props.datas.acceptUser = a.contactsName
                        props.datas.acceptTel = a.contactsPhone

                        props.datas.agentType = ''
                        props.datas.agentId = ''
                        props.datas.agentName = ''
                        props.datas.contractId = ''
                        data.agentOptions = []
                        data.contractOptions = []
                    }
                    if (props.datas.isSplit == 1){
                        getContract('distribute',props.datas.distributeId)
                    }

                } else {
                }
                emit('change')
            }

            const terminalChange = (val) => {
                const index = data.terminalOps.findIndex((a) => a.terminalId == val)
                if (index != -1) {
                    const a = data.terminalOps[index]
                    props.datas.acceptAddress =
                        a.provinceName + a.cityName + a.areaName + a.address
                    props.datas.acceptUser = a.contactsName
                    props.datas.acceptTel = a.contactsPhone

                    props.datas.agentType = ''
                    props.datas.agentId = ''
                    props.datas.agentName = ''
                    props.datas.contractId = ''
                    data.agentOptions = []
                    data.contractOptions = []
                }

                getContract('terminal',props.datas.terminalId)
                emit('change')
            }

            const addressConfirm = (str) => {
                props.datas.acceptAddress = str
                if (props.datas.acceptAddress) {
                    data.refForm.clearValidate('acceptAddress')
                }
            }

            const contactConfirm = (str) => {
                props.datas.acceptUser = str.linkmanName
                props.datas.acceptTel = str.tel

                if (props.datas.acceptUser) {
                    data.refForm.clearValidate('acceptUser')
                }
                if (props.datas.acceptTel) {
                    data.refForm.clearValidate('acceptTel')
                }
            }

            const typeChange = (val) => {
                if (props.datas.orderType == 1) {
                    if (!props.datas.distributeId) {
                        currentInstance.proxy.customMessage({
                            type: 'error',
                            message: '请先选择配送商',
                        })
                        props.datas.agentType = ''
                        return
                    }
                } else {
                    if (!props.datas.terminalId) {
                        currentInstance.proxy.customMessage({
                            type: 'error',
                            message: '请先选择终端',
                        })
                        props.datas.agentType = ''
                        return
                    }
                }

                data.contractOptions = []
                props.datas.agentId = ''
                props.datas.contractId = ''

                getAgent()
            }

            const getAgent = () => {
                if (props.datas.agentType) {
                    api.order.GET_ORDER_AGENT_LIST(props.datas).then((res) => {
                        if (!res.code && res.data) {
                            data.agentOptions = res.data.list
                        }
                    })
                }
            }

            const getTerminal = () => {
                api.order.GET_ORDER_TERMINAL_LIST().then((res) => {
                    if (!res.code && res.data) {
                        data.terminalOps = res.data.list
                    }
                })
            }

            const validate = () => {
                return new Promise((resolve, reject) => {
                    data.refForm.validate((val) => {
                        if (val) {
                            resolve()
                        } else {
                            reject
                        }
                    })
                })
            }

            const getDistribute = () => {
                api.order.GET_ORDER_DISTRIBUTE_LIST().then((res) => {
                    if (!res.code && res.data) {
                        data.distributeOps = res.data.list
                    }
                })
            }

            const querySearchAsyncSeller = async(queryString, cb) => {

                let results = []
                const res = await api.businessAgreement.BUSINESSAGREEMENT_SHANGPIN_LIST(queryString)
                if (!res.code && res.data) {
                    results = res.data.list || []
                }
                cb(results)
            }

            // 代理商事件
            const handleSelectSeller = (val) => {
                props.datas.sellerId = val.id
                props.datas.sellerName = val.sellerName
                props.datas.acceptAddress =
                    val.provinceName + val.cityName + val.areaName + val.address
                props.datas.acceptUser = val.userName
                props.datas.acceptTel = val.tel

                props.datas.contractId = ''
                data.contractOptions = []
                getContract('seller',props.datas.sellerId)
                emit('change')
            }

            // 获取代理商列表
            const querySearchAsyncAgent = async(queryString, cb) => {
                const a = {
                    keyWord: queryString,
                    agentType: props.datas.orderType == 3 ? 'agent' : ''
                }
                let results = []
                const res = await api.editorial.EDITORIAL_KEYWORDS(a)
                if (!res.code && res.data) {
                    results = res.data.list || []
                }
                cb(results)
            }

            // 代理商事件
            const handleSelectAgent = (val) => {
                props.datas.agentId = val.id
                props.datas.agentName = val.agentName
                props.datas.agentType = val.agentType
                if (val.agentType != 'agent'){
                    props.datas.agentName = val.userName
                }

                props.datas.contractId = ''
                data.contractOptions = []
                getContract(props.datas.agentType,props.datas.agentId)
                emit('change')
            }

            onMounted(() => {
                getTerminal()
                getAgent()
                getDistribute()
            })

            const getData = () => {
                console.log('getdata   ....', props.datas)
                getAgent()
                if (props.datas.orderType == 1){
                    if (props.datas.isSplit == 1 && props.datas.distributeId){
                        getContract('distribute',props.datas.distributeId)
                    }else if (props.datas.isSplit == 2 && props.datas.agentId) {
                        getContract(props.datas.agentType,props.datas.agentId)
                    }
                }else if (props.datas.orderType == 2){
                    getContract('terminal',props.datas.terminalId)
                }else if (props.datas.orderType == 3){
                    getContract(props.datas.agentType,props.datas.agentId)
                }

            }

            return {
                rules,
                types,
                clientOps,
                moneyTypes,
                ...toRefs(data),

                addressClick,
                contactClick,
                headChange,
                agentChange,
                typeChange,
                terminalChange,
                addressConfirm,
                contactConfirm,
                validate,
                distributeChange,
                getData,
                querySearchAsyncAgent,
                handleSelectAgent,
                querySearchAsyncSeller,
                handleSelectSeller,
                splitChange,
            }
        },
    })
</script>

<style lang="scss">
    .add-order-information-view {
        .el-form {
            .el-form-item {
                width: 100%;
                .el-form-item__content {
                    .el-select {
                        width: 100%;
                    }
                    .el-input {
                        width: 100%;
                    }
                }
            }
        }
    }
</style>
